package com.example.wjy;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.example.room.entity.Master;
import com.example.room.entity.TeamMember;
import com.example.superyi.myteam.R;
import com.example.wjy.adapter.MembersAdapter;
import com.example.wjy.viewmodels.MemberViewModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MembersActivity extends AppCompatActivity {


    RecyclerView recyclerView;
    Toolbar toolbar;
    String teamId;
    public static String url = "http://49.232.60.155:8080/AppServer_war/TeamServlet";
    public static List<TeamMember> masterList;
    MembersAdapter adapter;
    MemberViewModel memberViewModel;
    public SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_members);


        swipeRefreshLayout = findViewById(R.id.swipe);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                new MemberAsyncTask(memberViewModel, adapter).execute(teamId);
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        memberViewModel = new ViewModelProvider(this).get(MemberViewModel.class);
        recyclerView = findViewById(R.id.members);

//        masterList = new ArrayList<>();
        adapter = new MembersAdapter(memberViewModel.getAllTeamMember().getValue());
        recyclerView.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
        Intent intent = getIntent();
        teamId = intent.getStringExtra("teamId");
        /**
         * 因为是多线程请求数据库，所以在返回结果之前，masterList已经赋值给了adapter，
         * 因此可能要先保存到本地？
         */
//        new Thread(() -> {
//            OkHttpClient client = new OkHttpClient();
//            RequestBody requestBody = new FormBody.Builder()
//                    .add("teamId",teamId)
//                    .add("flag","0")
//                    .build();
//            Request request = new Request.Builder()
//                    .url(url)
//                    .post(requestBody)
//                    .build();
//            Call call = client.newCall(request);
//            call.enqueue(new Callback() {
//                @Override
//                public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
//                }
//
//                @Override
//                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                    String json = response.body().string();
//                    Log.d("member",json);
//                    Gson gson = new Gson();
//                    List<Master> masters = gson.fromJson(json,new TypeToken<List<Master>>(){}.getType());
////                    masterList = new ArrayList<>(masters);
////                    adapter.setMasterList(masters);
//                    //不能在非UI线程内更新UI
////                    adapter.notifyDataSetChanged();
//                    //不能在子线程更新LiveData?
//                    memberViewModel.getMasterList().setValue(masters);
//                    Log.d("member",masterList.get(0).getUserId());
//                }
//            });
//        }).start();

        new MemberAsyncTask(memberViewModel, adapter).execute(teamId);


        toolbar = findViewById(R.id.toolbar3);
        setSupportActionBar(toolbar);

        //这有问题，masterList是null
//        memberViewModel.getMasterList().observe(this,masterList -> {
//            adapter.setMasterList(masterList);
//            Log.d("member",String.valueOf(memberViewModel.getMasterList().getValue().size()));
//            adapter.notifyDataSetChanged();
//        });
//        Log.d("member","1111" + memberViewModel.getMasterList().getValue().size());

        memberViewModel.getAllTeamMember().observe(this, new Observer<List<TeamMember>>() {
            @Override
            public void onChanged(List<TeamMember> teamMembers) {
                adapter.setMasterList(teamMembers);
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.members_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.invite:
                Toast.makeText(this, "点击添加新成员", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class MemberAsyncTask extends AsyncTask<String, Void, List<TeamMember>> {

        List<TeamMember> masters;
        MemberViewModel memberViewModel;
        MembersAdapter adapter;

        public MemberAsyncTask(MemberViewModel memberViewModel, MembersAdapter adapter) {
            this.memberViewModel = memberViewModel;
            this.adapter = adapter;
        }

        @Override
        protected List<TeamMember> doInBackground(String... strings) {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new FormBody.Builder()
                    .add("teamId", strings[0])
                    .add("flag", "0")
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String json = response.body().string();
//                    Log.d("member", json);
                    Gson gson = new Gson();
                    masters = gson.fromJson(json, new TypeToken<List<TeamMember>>() {
                    }.getType());
//                    memberViewModel.insertTeamMember(masters.get(0),masters.get(1));
                    memberViewModel.deleteAllMaster();
                    for (int i = 0; i < masters.size(); ++i)
                        memberViewModel.insertTeamMember(masters.get(i));
                }
            });
            return masters;
        }

        @Override
        protected void onPostExecute(List<TeamMember> masters) {

        }
    }
}